﻿using System;
using System.Data;
using System.Transactions;
using System.Collections.Generic;
using Rainr.EFClient.Transaction;

namespace Rainr.EFClient
{
    /// <summary>
    /// 数据库访问分布式事务
    /// </summary>
    public class DbAccessorTransaction
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public DbAccessorTransaction()
        {
            this._DbAccessors = new List<IEntityTransaction>();
        }
        /// <summary>
        /// 加入需要分布式事务处理的数据访问者。
        /// </summary>
        /// <typeparam name="TAccessor">数据访问者类型</typeparam>
        /// <param name="accessor">数据访问者</param>
        public void EnlistAccessor<TAccessor>(TAccessor accessor) where TAccessor : IEntityTransaction
        {
            accessor.BeginTransaction();
            this._DbAccessors.Add(accessor);
        }
        /// <summary>
        /// 提交分布式事务。
        /// </summary>
        public void SubmitTransaction()
        {
            if (this._DbAccessors.Count > 0)
            {
                using (TransactionScope transaction = new TransactionScope())
                {
                    foreach (IEntityTransaction accessor in this._DbAccessors)
                    {
                        accessor.SubmitTransaction();
                    }
                    this._DbAccessors.Clear();
                    transaction.Complete();
                }
            }
        }
        /// <summary>
        /// 数据访问者集合
        /// </summary>
        private IList<IEntityTransaction> _DbAccessors;
    }
}
